<template>
  <div>
    <div class="text-h4 text-weight-bold q-mb-lg">留言板</div>
    
    <div class="row q-col-gutter-lg">
      <!-- 左侧：留言表单 -->
      <div class="col-12 col-md-5 col-lg-4">
        <q-card flat bordered class="message-form-card">
          <q-card-section>
            <div class="text-h6 q-mb-lg">
              <q-icon name="edit" /> 发表留言
            </div>
            
            <q-form @submit="submitMessage" class="q-gutter-md">
              <q-input
                v-model="form.name"
                label="昵称 *"
                :rules="[val => !!val || '请输入昵称']"
                outlined
                dense
              >
                <template v-slot:prepend>
                  <q-icon name="person" />
                </template>
              </q-input>
              
              <q-input
                v-model="form.email"
                label="邮箱 *"
                type="email"
                :rules="[
                  val => !!val || '请输入邮箱',
                  val => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val) || '邮箱格式不正确'
                ]"
                outlined
                dense
              >
                <template v-slot:prepend>
                  <q-icon name="email" />
                </template>
              </q-input>
              
              <q-input
                v-model="form.message"
                label="留言内容 *"
                type="textarea"
                :rules="[
                  val => !!val || '请输入留言内容',
                  val => val.length >= 5 || '留言内容至少需要5个字符'
                ]"
                rows="5"
                outlined
                counter
                maxlength="500"
              />
              
              <div class="text-right">
                <q-btn
                  type="submit"
                  color="primary"
                  label="发表留言"
                  :loading="isSubmitting"
                  :disable="!isFormValid"
                />
              </div>
            </q-form>
          </q-card-section>
        </q-card>
        
        <q-card flat bordered class="q-mt-md">
          <q-card-section>
            <div class="text-h6 q-mb-md">
              <q-icon name="info" /> 留言须知
            </div>
            <q-list dense>
              <q-item>
                <q-item-section avatar>
                  <q-icon color="primary" name="check_circle" />
                </q-item-section>
                <q-item-section>留言需要填写昵称和邮箱</q-item-section>
              </q-item>
              <q-item>
                <q-item-section avatar>
                  <q-icon color="primary" name="check_circle" />
                </q-item-section>
                <q-item-section>留言内容不少于5个字符</q-item-section>
              </q-item>
              <q-item>
                <q-item-section avatar>
                  <q-icon color="primary" name="check_circle" />
                </q-item-section>
                <q-item-section>请遵守互联网相关规定，文明发言</q-item-section>
              </q-item>
              <q-item>
                <q-item-section avatar>
                  <q-icon color="primary" name="check_circle" />
                </q-item-section>
                <q-item-section>管理员会定期审核留言内容</q-item-section>
              </q-item>
            </q-list>
          </q-card-section>
        </q-card>
      </div>
      
      <!-- 右侧：留言列表 -->
      <div class="col-12 col-md-7 col-lg-8">
        <q-card flat bordered class="message-list-card">
          <q-card-section>
            <div class="row items-center q-mb-md">
              <div class="col text-h6">
                <q-icon name="forum" /> 留言列表
              </div>
              <div class="col-auto">
                <q-select
                  v-model="sortBy"
                  :options="sortOptions"
                  outlined
                  dense
                  options-dense
                  style="width: 150px"
                />
              </div>
            </div>
            
            <q-separator class="q-mb-md" />
            
            <template v-if="messages.length > 0">
              <q-timeline color="primary">
                <q-timeline-entry
                  v-for="message in sortedMessages"
                  :key="message.id"
                  :title="message.name"
                  :subtitle="message.date"
                  avatar="https://ui-avatars.com/api/?name=me&color=fff&background=1976D2"
                >
                  <div>
                    <q-card flat bordered>
                      <q-card-section>
                        <div class="text-body1">{{ message.content }}</div>
                      </q-card-section>
                      
                      <q-separator v-if="message.reply" />
                      
                      <q-card-section v-if="message.reply" class="bg-grey-1">
                        <div class="row items-center q-mb-sm">
                          <q-icon name="reply" color="primary" size="sm" />
                          <span class="text-caption text-primary q-ml-xs">管理员回复：</span>
                        </div>
                        <div class="text-body2">{{ message.reply }}</div>
                      </q-card-section>
                      
                      <q-card-actions v-if="isAdmin && !message.reply" align="right">
                        <q-btn
                          flat
                          color="primary"
                          label="回复"
                          @click="openReplyDialog(message)"
                        />
                      </q-card-actions>
                      
                      <q-card-actions v-if="message.canDelete || isAdmin" align="right">
                        <q-btn
                          flat
                          color="negative"
                          icon="delete"
                          label="删除"
                          @click="confirmDelete(message.id)"
                        />
                      </q-card-actions>
                    </q-card>
                  </div>
                </q-timeline-entry>
              </q-timeline>
              
              <div class="text-center q-mt-lg">
                <q-pagination
                  v-if="totalPages > 1"
                  v-model="currentPage"
                  :max="totalPages"
                  direction-links
                  boundary-links
                  icon-first="first_page"
                  icon-last="last_page"
                  icon-prev="keyboard_arrow_left"
                  icon-next="keyboard_arrow_right"
                />
              </div>
            </template>
            
            <template v-else>
              <div class="text-center q-pa-xl">
                <q-icon name="forum" size="5rem" color="blue-grey-2" />
                <div class="text-h6 q-mt-md">暂无留言</div>
                <div class="text-grey-7 q-mt-sm">快来发表第一条留言吧！</div>
              </div>
            </template>
          </q-card-section>
        </q-card>
      </div>
    </div>
    
    <!-- 回复对话框 -->
    <q-dialog v-model="replyDialog.show" persistent>
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">回复留言</div>
        </q-card-section>
        
        <q-card-section>
          <q-input
            v-model="replyDialog.content"
            type="textarea"
            label="回复内容"
            autofocus
            outlined
            :rules="[val => !!val || '请输入回复内容']"
          />
        </q-card-section>
        
        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" @click="replyDialog.show = false" />
          <q-btn flat label="提交" color="primary" @click="submitReply" :loading="replyDialog.submitting" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    
    <!-- 删除确认对话框 -->
    <q-dialog v-model="deleteDialog.show" persistent>
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar icon="delete" color="negative" text-color="white" />
          <span class="text-h6 q-ml-md">确定要删除这条留言吗？</span>
        </q-card-section>
        
        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" @click="deleteDialog.show = false" />
          <q-btn flat label="删除" color="negative" @click="deleteMessage" :loading="deleteDialog.loading" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表单数据
const form = ref({
  name: '',
  email: '',
  message: ''
})

// 留言列表数据
const messages = ref([
  {
    id: 1,
    name: '张三',
    email: 'zhangsan@example.com',
    content: '网站设计得非常棒，内容也很丰富！希望以后能有更多关于前端开发的文章分享。',
    date: '2024-03-16 14:30',
    canDelete: false,
    reply: '感谢您的支持！我会继续努力创作更多优质内容。'
  },
  {
    id: 2,
    name: '李四',
    email: 'lisi@example.com',
    content: '我很喜欢这个网站的设计风格，简洁大方，内容也很有深度。期待更多技术分享！',
    date: '2024-03-15 15:45',
    canDelete: false
  },
  {
    id: 3,
    name: '王五',
    email: 'wangwu@example.com',
    content: '最近在学习Vue 3和TypeScript，这个网站给了我很多启发。能不能出一些关于Vue 3 + TypeScript的教程？',
    date: '2024-03-14 10:20',
    canDelete: false,
    reply: '已经计划了相关内容，敬请期待！'
  }
])

// 分页和排序
const pageSize = 10
const currentPage = ref(1)
const sortBy = ref('newest')
const sortOptions = [
  { label: '最新优先', value: 'newest' },
  { label: '最早优先', value: 'oldest' },
]

// 状态管理
const isSubmitting = ref(false)
const isAdmin = ref(false) // 在实际应用中，这应该根据登录状态来设置

// 对话框
const replyDialog = ref({
  show: false,
  messageId: null,
  content: '',
  submitting: false
})

const deleteDialog = ref({
  show: false,
  messageId: null,
  loading: false
})

// 计算属性
const isFormValid = computed(() => {
  return !!form.value.name && 
         !!form.value.email && 
         /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email) && 
         !!form.value.message && 
         form.value.message.length >= 5
})

const totalPages = computed(() => Math.ceil(messages.value.length / pageSize))

const sortedMessages = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  
  // 克隆数组以避免修改原始数据
  const sorted = [...messages.value]
  
  // 按日期排序
  if (sortBy.value === 'newest') {
    sorted.sort((a, b) => new Date(b.date) - new Date(a.date))
  } else {
    sorted.sort((a, b) => new Date(a.date) - new Date(b.date))
  }
  
  return sorted.slice(start, end)
})

// 方法
const submitMessage = async () => {
  if (!isFormValid.value) return
  
  isSubmitting.value = true
  
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 添加新留言
    const newMessage = {
      id: Date.now(),
      name: form.value.name,
      email: form.value.email,
      content: form.value.message,
      date: new Date().toLocaleString(),
      canDelete: true
    }
    
    messages.value.unshift(newMessage)
    
    // 重置表单
    form.value = {
      name: '',
      email: '',
      message: ''
    }
    
    // 显示成功提示
    $q.notify({
      color: 'positive',
      position: 'top',
      message: '留言发表成功！',
      icon: 'check_circle'
    })
  } catch (error) {
    console.error('提交留言失败:', error)
    $q.notify({
      color: 'negative',
      position: 'top',
      message: '留言发表失败，请稍后重试！',
      icon: 'error'
    })
  } finally {
    isSubmitting.value = false
  }
}

const openReplyDialog = (message) => {
  replyDialog.value = {
    show: true,
    messageId: message.id,
    content: '',
    submitting: false
  }
}

const submitReply = async () => {
  if (!replyDialog.value.content) return
  
  replyDialog.value.submitting = true
  
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 更新留言回复
    const messageIndex = messages.value.findIndex(m => m.id === replyDialog.value.messageId)
    if (messageIndex !== -1) {
      messages.value[messageIndex].reply = replyDialog.value.content
    }
    
    // 关闭对话框
    replyDialog.value.show = false
    
    // 显示成功提示
    $q.notify({
      color: 'positive',
      position: 'top',
      message: '回复成功！',
      icon: 'check_circle'
    })
  } catch (error) {
    console.error('提交回复失败:', error)
    $q.notify({
      color: 'negative',
      position: 'top',
      message: '回复失败，请稍后重试！',
      icon: 'error'
    })
  } finally {
    replyDialog.value.submitting = false
  }
}

const confirmDelete = (messageId) => {
  deleteDialog.value = {
    show: true,
    messageId,
    loading: false
  }
}

const deleteMessage = async () => {
  deleteDialog.value.loading = true
  
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 删除留言
    messages.value = messages.value.filter(msg => msg.id !== deleteDialog.value.messageId)
    
    // 关闭对话框
    deleteDialog.value.show = false
    
    // 显示成功提示
    $q.notify({
      color: 'positive',
      position: 'top',
      message: '留言已删除！',
      icon: 'check_circle'
    })
  } catch (error) {
    console.error('删除留言失败:', error)
    $q.notify({
      color: 'negative',
      position: 'top',
      message: '删除失败，请稍后重试！',
      icon: 'error'
    })
  } finally {
    deleteDialog.value.loading = false
  }
}

// 监听当前页变化，确保页面滚动到顶部
watch(currentPage, () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
})
</script>

<style scoped>
.message-form-card,
.message-list-card {
  border-radius: 8px;
}

.q-timeline__entry {
  margin-bottom: 24px;
}
</style> 